package com.xiaotu.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import tk.mybatis.spring.annotation.MapperScan;

import javax.sql.DataSource;

@Configuration
//扫描 Mapper 接口并容器管理
@MapperScan(basePackages = {"com.xiaotu.dao.mysql8"}, sqlSessionFactoryRef = "mysql8SqlSessionFactory")
public class Mysql8DataSourceConfig {

    @Value("${mysql8.datasource.url}")
    private String url;

    @Value("${mysql8.datasource.username}")
    private String user;

    @Value("${mysql8.datasource.password}")
    private String password;

    @Value("${mysql8.datasource.driverClassName}")
    private String driverClass;

    @Bean(name = "mysql8DataSource")
    public DataSource mysql8DataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean(name = "mysql8TransactionManager")
    @Primary
    public DataSourceTransactionManager mysql8TransactionManager() {
        return new DataSourceTransactionManager(mysql8DataSource());
    }

    @Bean(name = "mysql8SqlSessionFactory")
    @Primary
    public SqlSessionFactory mysqlSqlSessionFactory(@Qualifier("mysql8DataSource") DataSource mysql8DataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(mysql8DataSource);
        return sessionFactory.getObject();
    }
}